package com.xinhe.web.service;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.xinhe.web.common.BusinessException;
import com.xinhe.web.common.Result;
import com.xinhe.web.entity.*;
import com.xinhe.web.reposity.IdentityRepository;
import com.xinhe.web.reposity.MemberRepository;
import com.xinhe.web.response.IdentityView;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import javax.inject.Provider;
import javax.persistence.EntityManager;
import java.util.Set;
@Service

public class IdentityService {
    private static final String CHARSET = "UTF-8";
    @Autowired
    private IdentityRepository identityRepository;
    /*@Autowired
    private IUserSessionManager userSessionManager;*/
    @Autowired
    private MemberRepository memberRepository;
    //查询工厂
    private JPAQueryFactory queryFactory;
    @Autowired
    private Provider<EntityManager> entityManager;
    @PostConstruct
    public void init() {
        queryFactory = new JPAQueryFactory(entityManager);
    }

    public QueryResults<IdentityView> pageIdentity(String queryWord,String checkStatus,
                                                   int pageNum, int pageSize) {
        QIdentity qIdentity = QIdentity.identity;
        QMember qMember = QMember.member;
        BooleanBuilder builder = new BooleanBuilder();
        //builder.and(qGoods.removed.eq(0));
        return queryFactory.select(
                        Projections.bean(
                                IdentityView.class,
                                qIdentity.name,
                                qIdentity.fUserId,
                                qIdentity.id,
                                qIdentity.card,
                                qIdentity.checkStatus,
                                qIdentity.name,
                                qIdentity.checkRemark,
                                qIdentity.certificateBack,
                                qIdentity.certificateFront,
                                qMember.name.as("userName"),
                                qMember.mobile.as("phone")
                        )
                ).from(qIdentity)
                .leftJoin(qMember).on(qIdentity.fUserId.eq(qMember.fUserId))
                .where(builder).offset(pageNum * pageSize).limit(pageSize).fetchResults();
    }


    @Transactional(rollbackFor = {Exception.class})
    public Result saveIdentity(Long userId,String name,String card,String certificateFront,String certificateBack, String gender) {
        //Long userId = this.userSessionManager.getUserId();
        Identity identity = this.identityRepository.findByUserId(userId);
        Integer count = this.identityRepository.findByCode(card);
        if (count.intValue() > 0) {
            throw new BusinessException(11001,"该身份证已实名认证过,请重新更换身份证");
        }
        if (identity != null) {
            if (identity.getCheckStatus().equals("SUCCESS"))
                throw new BusinessException(11002,"您提交的实名认证已通过，请不要重复提交");
            if (identity.getCheckStatus().equals("NONE")) {
                throw new BusinessException(11003,"您已提交过实名认证申请,请不要重复提交");
            }
        }
        identity = new Identity();
        identity.setCard(card);
        identity.setName(name);
        identity.setCertificateBack(certificateBack);
        identity.setCertificateFront(certificateFront);
        identity.setCheckStatus("SUCCESS");
        identity.setCheckRemark(null);
        identity.setfUserId(userId);
        this.identityRepository.save(identity);
        Member member = this.memberRepository.findByUserId(userId);
        if ("男".equals(gender)) {
            member.setGender(Integer.valueOf(1));
        } else {
            member.setGender(Integer.valueOf(2));
        }
        this.memberRepository.saveAndFlush(member);
        return Result.ok();
    }


    public Result<Identity> findIdentityByUserId(Long userId) {
        /*if (userId == null) {
            userId = this.userSessionManager.getUserId();
        }*/
        Identity identity = this.identityRepository.findByUserId(userId);
        return Result.ok(identity);
    }

    @Transactional
    public Result updateIdentityStatus(Long id) {
        Identity identity = identityRepository.findById(id).get();
        identity.setCheckStatus("FAILURE");
        identityRepository.saveAndFlush(identity);
        return Result.ok();
    }

    @Transactional
    public Result saveCheck(Set<Long> identityIds,String status,String remark) {
        if (CollectionUtils.isNotEmpty(identityIds)) {
            for (Long identityId : identityIds) {
                Identity identity = (Identity)this.identityRepository.findById(identityId).get();
                identity.setRemark(remark);
                identity.setCheckStatus(status);
                this.identityRepository.saveAndFlush(identity);
                if ("SUCCESS".equals(status)) {
                    Member member = this.memberRepository.findByUserId(identity.getfUserId());
                    if (StringUtils.isEmpty(member.getName())) {
                        member.setName(identity.getName());
                        this.memberRepository.saveAndFlush(member);
                    }
                }
            }
        }
        return Result.ok();
    }

    public Result<Identity> findById(Long identityId) {
        return Result.ok(identityRepository.findById(identityId).get());
    }

    public Result delete(Long identityId) {
        identityRepository.deleteById(identityId);
        return Result.ok();
    }
}
